package com.spring.pick2pick;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spring.pick2pick.common.MultipartBox;
import com.spring.pick2pick.common.PageHandler;
import com.spring.pick2pick.common.PatternChecker;
import com.spring.pick2pick.common.Util;
import com.spring.pick2pick.dao.CommonDao;
import com.spring.pick2pick.dao.SportDao;
import com.spring.pick2pick.dao.TeamDao;
import com.spring.pick2pick.model.FileInfo;
import com.spring.pick2pick.model.TeamItem;

@Controller
public class TeamController {
	
	@Autowired
	TeamDao teamDao;
	@Autowired
	CommonDao commonDao;
	@Autowired
	SportDao sportDao;
	
	/** 리그 리스트 목록 */
	@RequestMapping(value = "listTeam", method = RequestMethod.GET)
	public String listTeam(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		int page = 1;
		int size = 10;
		String pageStr = request.getParameter("page");
		
		if (pageStr != null) {
			page = Integer.parseInt(pageStr);
		}
		
		String[] where = where(model, request, response);
		
		model.addAttribute("toggle", commonDao.getCommonText("팀검색"));
		
		if (where == null) {
			model.addAttribute("displayCount", teamDao.getDisplayCount(null));
			model.addAttribute("unDisplayCount", teamDao.getUnDisplayCount(null));
			model.addAttribute("list", teamDao.getTeamList(page, size, null, "t.idTeam DESC"));
		} else {
			model.addAttribute("displayCount", teamDao.getDisplayCount(where[0]));
			model.addAttribute("unDisplayCount", teamDao.getUnDisplayCount(where[0]));
			model.addAttribute("list", teamDao.getTeamList(page, size, where[0], "t.idTeam DESC"));
		}
		
		model.addAttribute("page", PageHandler.getInstance());
		model.addAttribute("sportList", sportDao.getSportList("ASC"));
		
		if (where[0] != null) model.addAttribute("where", where[1]);
		
		return "team/listTeam";
	}
	
	/** 팀 추가 */
	@RequestMapping(value = "addTeam", method = RequestMethod.GET)
	public String addTeam(Locale locale, Model model) {
		
		model.addAttribute("sportList", sportDao.getSportList("ASC"));
		
		return "team/addTeam";
	}
	
	/** 팀 추가후 리스트 */
	@RequestMapping(value = "addTeamOk", method = RequestMethod.POST)
	public String addTeamOk(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		MultipartBox mbox = MultipartBox.getInstance("/upload/team");
		FileInfo finfo = mbox.upload2(request);
		
		String teamName = mbox.getValue("teamName");
		teamName = teamName.replace("&", "&amp;");
		teamName = teamName.replace("<", "&lt;");
		teamName = teamName.replace(">", "&gt;");
		String teamNameSimple = mbox.getValue("teamNameSimple");
		teamNameSimple = teamNameSimple.replace("&", "&amp;");
		teamNameSimple = teamNameSimple.replace("<", "&lt;");
		teamNameSimple = teamNameSimple.replace(">", "&gt;");
		String leagueStr = mbox.getValue("league");
		
		if (teamName == null || teamNameSimple == null || leagueStr == null || finfo == null ||
				teamName.equals("") || teamNameSimple.equals("") || leagueStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
			return null;
		}
		
		int idLeague = Integer.parseInt(leagueStr);
		
		TeamItem item = new TeamItem();
		item.setTeamName(teamName);
		item.setTeamNameSimple(teamNameSimple);
		item.setIdLeague(idLeague);
		item.setFinfo(finfo);
		
		int result = teamDao.addTeam(item);
		
		if (result > 0) {
			try {
				response.sendRedirect("listTeam");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			Util.getInstance().alertPage("추가에 실패하였습니다.", response);
		}
		
		return null;
	}
	
	/** 팀 수정후 리스트 */
	@RequestMapping(value = "editTeamOk", method = RequestMethod.POST)
	public String editTeamOk(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		MultipartBox mbox = MultipartBox.getInstance("/upload/team");
		FileInfo finfo = mbox.upload2(request);
		
		int idTeam = mbox.getInt("idTeam");
		int isDisplay = mbox.getInt("isDisplay");
		int idImage = mbox.getInt("image");
		String teamName = mbox.getValue("teamName");
		teamName = teamName.replace("&", "&amp;");
		teamName = teamName.replace("<", "&lt;");
		teamName = teamName.replace(">", "&gt;");
		String teamNameSimple = mbox.getValue("teamNameSimple");
		teamNameSimple = teamNameSimple.replace("&", "&amp;");
		teamNameSimple = teamNameSimple.replace("<", "&lt;");
		teamNameSimple = teamNameSimple.replace(">", "&gt;");
		String leagueStr = mbox.getValue("league");
		int page = mbox.getInt("page");
		String where = mbox.getValue("where");
		
		boolean whereCheck = false;
		
		String[] arr = where.substring(1, where.length()).split("&");
		for (int i=0; i<arr.length; i++) {
			String[] temp = arr[i].split("=");
			if (temp[0].equals("teamName")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null")) {
					
					String teamNameStr = where.substring(where.indexOf("teamName=") + 9, where.indexOf("&regDate1="));
					try {
						String teamNameNew = URLEncoder.encode(teamNameStr, "utf-8");
						where = where.replace(teamNameStr, teamNameNew);
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					
					whereCheck = true;
				}
			} else if (temp[0].equals("regDate1")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("regDate2")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("sport")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null") && !temp[1].equals("default")) {
					whereCheck = true;
				}
			} else if (temp[0].equals("league")) {
				if (temp.length > 1 && temp[1] != null && !temp[1].equals("") && !temp[1].equals("null") && !temp[1].equals("default")) {
					whereCheck = true;
				}
			}
		}
		
		if (teamName == null || teamNameSimple == null || leagueStr == null || teamName.equals("") || teamNameSimple.equals("") || leagueStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
			return null;
		}
		
		int idLeague = Integer.parseInt(leagueStr);
		
		TeamItem item = new TeamItem();
		item.setIdTeam(idTeam);
		item.setIsDisplay(isDisplay);
		item.setTeamName(teamName);
		item.setTeamNameSimple(teamNameSimple);
		item.setIdLeague(idLeague);
		item.setFinfo(finfo);
		item.setIdImage(idImage);
		
		int result = teamDao.editTeam(item);
		
		if (result > 0) {
			try {
				if (whereCheck) {
					response.sendRedirect("listTeam?page=" + page + "&where=" + where);
				} else {
					response.sendRedirect("listTeam?page=" + page);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			Util.getInstance().alertPage("수정에 실패하였습니다.", response);
		}
		
		return null;
	}
	
	/** 팀 전시여부 변경 */
	@RequestMapping(value = "displayTeam", method = RequestMethod.GET)
	public String displayTeam(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		String pageStr = request.getParameter("page");
		String idStr = request.getParameter("id");
		String isDisplayStr = request.getParameter("isDisplay");
		String[] where = where(model, request, response);
		
		if (pageStr == null || idStr == null || isDisplayStr == null || pageStr.equals("") || idStr.equals("") || isDisplayStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
		} else {
			int page = Integer.parseInt(pageStr);
			int id = Integer.parseInt(idStr);
			int isDisplay = Integer.parseInt(isDisplayStr);
			
			if (isDisplay == 0) {
				isDisplay = 1;
			} else if (isDisplay == 1) {
				isDisplay = 0;
			}
			
			TeamItem item = new TeamItem();
			item.setIdTeam(id);
			item.setIsDisplay(isDisplay);
			int result = teamDao.editDisplay(item);
			
			if (result > 0) {
				
				String html = "<!doctype html>";
				html += "<head>";
				html += "<meta charset='utf-8'>";
				html += "<script>";
				html += "alert('정상적으로 수정되었습니다.');";
				if (where[0] == null) {
					html += "location.replace('listTeam?page=" + page + "');";
				} else {
					html += "location.replace('listTeam?page=" + page + "&where=" + where[1] + "');";
				}
				html += "</script>";
				html += "</head>";
				html += "</html>";
				
				try {
					response.setCharacterEncoding("utf-8");
					PrintWriter out = response.getWriter();
					out.print(html);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				Util.getInstance().alertPage("전시여부 수정에 실패하였습니다.", response);
			}
			
		}
		return null;
	}
	
	/** 팀 검색 */
	@RequestMapping(value = "searchTeam", method = RequestMethod.GET)
	public String searchTeam(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		String[] where = where(model, request, response);
		
		if (where == null) {
			return null;
		}
		
		model.addAttribute("toggle", commonDao.getCommonText("팀검색"));
		model.addAttribute("displayCount", teamDao.getDisplayCount(where[0]));
		model.addAttribute("unDisplayCount", teamDao.getUnDisplayCount(where[0]));
		model.addAttribute("list", teamDao.getTeamList(1, 10, where[0], "t.idTeam DESC"));
		model.addAttribute("page", PageHandler.getInstance());
		model.addAttribute("sportList", sportDao.getSportList("ASC"));
		model.addAttribute("where", where[1]);
		
		return "team/listTeam";
	}
	
	/** 팀 조회 */
	@RequestMapping(value = "viewTeam", method = RequestMethod.GET)
	public String viewTeam(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		int page = 1;
		String idStr = request.getParameter("id");
		String pageStr = request.getParameter("page");
		
		String[] where = where(model, request, response);
		
		if (idStr == null || idStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
			return null;
		} else {
			int id = Integer.parseInt(idStr);
			if (pageStr != null) {
				page = Integer.parseInt(pageStr);
			}
			
			TeamItem item = new TeamItem();
			item.setIdTeam(id);
			
			TeamItem result = teamDao.getTeam(item);
			model.addAttribute("item", result);
			model.addAttribute("page", page);
			model.addAttribute("where", where[1]);
			
			model.addAttribute("sportList", sportDao.getSportList("ASC"));
		}
		
		return "team/viewTeam";
	}
	
	public String[] where(Model model, HttpServletRequest request, HttpServletResponse response) {
		
		String where = null;
		
		String teamName = request.getParameter("teamName");
		
		if (teamName != null && !teamName.equals("") && !teamName.equals("null")) {
			try {
				teamName = URLDecoder.decode(teamName, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			model.addAttribute("teamName", teamName);
			if (where == null) where = "";
			where += " AND t.teamName like '%" + teamName + "%'";
		}
		
		String sport = request.getParameter("sport");
		if (sport != null && !sport.equals("default") && !sport.equals("null")) {
			model.addAttribute("sport", sport);
			if (where == null) where = "";
			where += " AND l.idSport=" + sport;
		}
		
		String league = request.getParameter("league");
		if (league != null && !league.equals("default") && !league.equals("null")) {
			model.addAttribute("league", league);
			if (where == null) where = "";
			where += " AND l.idLeague=" + league;
		}
		
		PatternChecker checker = PatternChecker.getInstance();
		String regDate1 = request.getParameter("regDate1");
		String regDate2 = request.getParameter("regDate2");
		String regDate1Str = null, regDate2Str = null;
		if (regDate1 != null && !regDate1.equals("") && !regDate1.equals("null")) {
			regDate1Str = regDate1.replace("-", "");
			if (regDate1Str.length() != 8 || !checker.isNum(regDate1Str)) {
				Util.getInstance().alertPage("등록일 시작을 yyyy-mm-dd 포맷으로 입력해주세요.", response);
				return null;
			}
		}
		if (regDate2 != null && !regDate2.equals("") && !regDate2.equals("null")) {
			regDate2Str = regDate2.replace("-", "");
			if (regDate2Str.length() != 8 || !checker.isNum(regDate2Str)) {
				Util.getInstance().alertPage("등록일 끝을 yyyy-mm-dd 포맷으로 입력해주세요.", response);
				return null;
			}
		}
		
		if (regDate1Str != null && regDate1Str.length() == 8 && checker.isNum(regDate1Str) && regDate2Str != null && regDate2Str.length() == 8 && checker.isNum(regDate2Str)) {
			if (where == null) where = "";
			model.addAttribute("regDate1", regDate1);
			model.addAttribute("regDate2", regDate2);
			where += " AND t.regDate BETWEEN " + regDate1Str + "000000 AND " + regDate2Str + "999999";
		} else if (regDate1Str != null && regDate1Str.length() == 8 && checker.isNum(regDate1Str)) {
			if (where == null) where = "";
			model.addAttribute("regDate1", regDate1);
			where += " AND t.regDate > " + regDate1Str + "000000";
		} else if (regDate2Str != null && regDate2Str.length() == 8 && checker.isNum(regDate2Str)) {
			if (where == null) where = "";
			model.addAttribute("regDate2", regDate2);
			where += " AND t.regDate < " + regDate2Str + "999999";
		}
		
		String result[] = new String[2];
		result[0] = where;
		if (teamName != null && !teamName.equals("") && !teamName.equals("null")) {
			try {
				teamName = URLEncoder.encode(teamName, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		result[1] = "&teamName=" + teamName + "&regDate1=" + regDate1 + "&regDate2=" + regDate2 + "&sport=" + sport + "&league=" + league;
		
		return result;
	}
	
}
